|
|
|
|
|
|
|
This sample program is very simple; it has only two forms with no controls. To create it, follow these steps: |
|
|
|
|
|
|
|
|
1. Open Visual Basic and create a new Standard EXE project. |
|
|
|
|
|
|
|
|
2. Double-click Form1 to bring up its Code window. |
|
|
|
|
|
|
|
|
3. Make sure the Load event is selected in the drop-down Event box at the upper-right of the Code window. |
|
|
|
|
|
|
|
|
4. Type the statement MsgBox "The Form Load Event occurred" into the event procedure so that the code looks like this: |
|
|
|
 |
|
|
|
|
Private Sub Form_Load()
MsgBox "The Form Load Event occurred "
End Sub |
|
|
|
|
|
|
|
|
5. Repeat steps 3 and 4 to place similar MsgBox statements in the Initialize and Unload event procedures. |
|
|
|
|
|
|
|
|
6. Add a second form, Form2, to the project by choosing Project, Add Form. |
|
|
|
|
|
|
|
|
Now that you have created the project, press F5 to run it. Notice that the Initialize event comes first, followed by the Load event. Click the form's Close button, and you should notice that the Unload and Terminate events occur before the program stops. |
|
|
|
|
|
|
|
|
Now start the program again and press Ctrl+Break to pause execution. Press Ctrl+G to bring up the Immediate window. Put the cursor in the Immediate window, and enter the following lines (pressing Enter after each), observing the messages that appear: |
|
|
|
|
|
|
|
|
Load Form2
Unload Form1
Load Form1 |
|
|
|
|
|
|
|
|
(You load Form2 to prevent the program from ending when you unload Form1.) You should have noticed that the Initialize event did not occur when Form1 was loaded the second time. Now enter the following lines: |
|
|
|
|
|
|
|
|
Unload Form1
Set Form1 = Nothing |
|
|
|
|
|
|
|
|
Setting an instance of a form to Nothing when you're done with it is good practice. This way, you can ensure that all resources that were allocated to the form are properly released. |
|
|
|
|
|
|
|
|
The Initialize event occurs again because the instance of Form1 that you created before was destroyed when it was set to Nothing. |
|
|
|
|
|
|
|
|
You can use program code in these events to set the properties of the form or any of its controls, set up databases or recordsets needed for the form, or run any other code that you might find necessary. The Load and Unload events each occur only once in the life of a formwhen the form is loaded and unloaded from memory, respectively. On the other hand, the Activate and Deactivate events can occur many times. Therefore, you need to be careful which code is placed in which event. |
|
|
|
|
|